package cn.wolfcode.wolf2w.business.service.impl;

import cn.wolfcode.wolf2w.api.domain.StrategyCatalog;
import cn.wolfcode.wolf2w.business.api.RemoteDestinationService;
import cn.wolfcode.wolf2w.business.api.domain.Destination;
import cn.wolfcode.wolf2w.business.api.domain.Strategy;
import cn.wolfcode.wolf2w.business.api.domain.StrategyContent;
import cn.wolfcode.wolf2w.business.api.domain.StrategyTheme;
import cn.wolfcode.wolf2w.business.mapper.*;
import cn.wolfcode.wolf2w.business.query.StrategyQuery;
import cn.wolfcode.wolf2w.business.service.IStrategyService;
import cn.wolfcode.wolf2w.business.util.DateUtil;
import cn.wolfcode.wolf2w.common.core.context.SecurityContextHolder;
import cn.wolfcode.wolf2w.common.core.domain.R;
import cn.wolfcode.wolf2w.common.redis.service.RedisService;
import cn.wolfcode.wolf2w.common.redis.utils.RedisKeys;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.yaml.snakeyaml.events.Event;

import java.util.*;
import java.util.concurrent.TimeUnit;


/**
 * 攻略Service业务层处理
 *
 * @author 沙琪玛
 * @date 2024-11-01
 */
@Service
@Transactional
public class StrategyServiceImpl extends ServiceImpl<StrategyMapper, Strategy> implements IStrategyService {

    @Autowired
    private StrategyCatalogMapper strategyCatalogMapper;
    @Autowired
    private StrategyThemeMapper strategyThemeMapper;
    @Autowired
    private StrategyContentMapper strategyContentMapper;
    @Autowired
    private RemoteDestinationService remoteDestinationService;
    @Autowired
    private RedisService redisService;


    @Autowired
    private AmqpTemplate amqpTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public Map<String, Object> viewnumIncr(Long sid) {
        String key = getString(sid);

        redisService.incrementCacheMapValue(key, "viewnum", 1);
        Map<String, Object> cacheMap = redisService.getCacheMap(key);
        return cacheMap;
    }

    @Override
    public Map<String, Object> thumbsup(Long sid) {
        Long uid = SecurityContextHolder.getUserId();
        String key = RedisKeys.STRATEGY_THUMBSUP.join(sid.toString(), uid.toString());
        if (!redisService.hasKey(key)){
            Date date = new Date();
            Date end = DateUtil.getEndDate(date);
            long time = DateUtil.getDateBetween(end, end);
            if (time == 0){
                time++ ;
            }
            redisService.setCacheObject(key,0,time, TimeUnit.SECONDS);
        }
        boolean flg = false;
        Long ret = redisService.incrementCacheObjectValue(key,1);
        String statiskey = RedisKeys.STRATEGY_STATIS_HASH.join(sid.toString());
        if (ret > 5){
            //点赞失败 今天已经超过五次

        }else{
            //点赞成功
            flg=true;
            redisService.incrementCacheMapValue(statiskey,"thumbsupnum",1);
        }
        Map<String, Object> cacheMap = redisService.getCacheMap(statiskey);
        cacheMap.put("result",flg);

        return cacheMap;
    }

    @Override
    public boolean isUserFavor(Long sid, Long uid) {
        String key = RedisKeys.STRATEGY_FAVOR.join(uid.toString());
        if (redisService.hasKey(key)){
            Set<Long> sids = new HashSet<>();
            sids.add(-1L);
            redisService.setCacheSet(key,sids);

        }
        return redisService.isCacheSetContains(key,sid);
    }

    @Override
    public void statisHashPersistence() {
        String join = RedisKeys.STRATEGY_STATIS_HASH.join("*");
        Collection<String> keys = redisService.keys(join);
        if (keys != null && keys.size() > 0) {
            for (String key : keys) {
                Map<String, Object> map = redisService.getCacheMap(key);
                lambdaUpdate().eq(Strategy::getId, map.get("id"))
                        .set(Strategy::getViewnum, map.get("viewnum"))
                        .set(Strategy::getReplynum, map.get("replynum"))
                        .set(Strategy::getSharenum, map.get("sharenum"))
                        .set(Strategy::getFavornum, map.get("favornum"))
                        .set(Strategy::getThumbsupnum, map.get("thumbsupnum"))
                        .update();
            }
        }
        System.out.println("攻略统计数据持久化完成///");
    }

    private String getString(Long sid) {
        String key = RedisKeys.STRATEGY_STATIS_HASH.join(sid.toString());
        if (!redisService.hasKey(key)) {
            Strategy strategy = baseMapper.selectById(sid);
            Map<String, Object> map = new HashMap<>();
            map.put("viewnum", Integer.valueOf(strategy.getViewnum().toString()));
            map.put("replynum", Integer.valueOf(strategy.getReplynum().toString()));
            map.put("favornum", Integer.valueOf(strategy.getFavornum().toString()));
            map.put("sharenum", Integer.valueOf(strategy.getSharenum().toString()));
            map.put("thumbsupnum", Integer.valueOf(strategy.getThumbsupnum().toString()));
            map.put("id", strategy.getId());
            redisService.setCacheMap(key, map);
        }
        return key;
    }

    @Override
    public void insert(Strategy strategy) {
        StrategyTheme theme = strategyThemeMapper.selectById(strategy.getThemeId());
        strategy.setThemeName(theme.getName());
        StrategyCatalog catalog = strategyCatalogMapper.selectById(strategy.getCatalogId());
        strategy.setCatalogName(catalog.getName());
        strategy.setDestId(catalog.getDestId());
        strategy.setDestName(catalog.getDestName());
        strategy.setCreateTime(new Date());

        // TODO: 2024/11/5   isabroad
        R<List<Destination>> inner = remoteDestinationService.getToasts(strategy.getDestId(), "inner");
        List<Destination> data = inner.getData();
        if ("中国".equals(data.get(0).getName())) {
            strategy.setIsabroad(0L);
        } else {
            strategy.setIsabroad(1L);
        }

        strategy.setViewnum(0l);
        strategy.setReplynum(0l);
        strategy.setSharenum(0l);
        strategy.setFavornum(0l);
        strategy.setThumbsupnum(0l);
        baseMapper.insert(strategy);
        Long strategyId = strategy.getId();
        StrategyContent content = new StrategyContent();
        content.setId(strategyId);
        content.setContent(strategy.getContent().getContent());
        strategyContentMapper.insert(content);

        String message = JSON.toJSONString(strategy);
        amqpTemplate.convertAndSend("travelExchange","",message);



    }

    @Override
    public IPage<Strategy> queryPage(StrategyQuery qo) {
        IPage<Strategy> page = new Page<>(qo.getCurrentPage(), qo.getPageSize());
        LambdaQueryWrapper<Strategy> qw = new LambdaQueryWrapper<>();
        if (qo.getType() != null) {
            if (qo.getType() == 1 || qo.getType() == 2) {
                qw.eq(Strategy::getDestId, qo.getRefid());
            } else if (qo.getType() == 3) {
                qw.eq(Strategy::getThemeId, qo.getRefid());
            }
        }

        return baseMapper.selectPage(page, qw);
    }

    @Override
    public List<StrategyCatalog> queryCatalogList(Long destId) {
        LambdaQueryWrapper<StrategyCatalog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrategyCatalog::getDestId, destId);

        List<StrategyCatalog> list = strategyCatalogMapper.selectList(queryWrapper);
        for (StrategyCatalog catalog : list) {
            List<Strategy> strategies = lambdaQuery().eq(Strategy::getCatalogId, catalog.getId()).list();
            catalog.setStrategies(strategies);
        }
        return list;
    }

    @Override
    public Map<String, Object> replynumIncr(Long sid) {
        String key = getString(sid);

        redisService.incrementCacheMapValue(key, "replynum", 1);
        Map<String, Object> cacheMap = redisService.getCacheMap(key);
        return cacheMap;

    }

    @Override
    public List<Strategy> getViewnnumTop3(Long destId) {
        return lambdaQuery()
                .eq(Strategy::getDestId, destId)
                .last("limit 3")
                .orderByDesc(Strategy::getViewnum)
                .list();
    }

    @Override
    public Map<String, Object> favor(Long sid) {
        Long uid = SecurityContextHolder.getUserId();
        String key = RedisKeys.STRATEGY_FAVOR.join(uid.toString());
        if (redisService.hasKey(key)){
            Set<Long> sids = new HashSet<>();
            sids.add(-1L);
            redisService.setCacheSet(key,sids);
        }
        String statisKey = RedisKeys.STRATEGY_STATIS_HASH.join(sid.toString());
        boolean result = false;
        if (redisService.isCacheSetContains(key,sid)){
            //当前是取消操作
            redisService.incrementCacheMapValue(statisKey,"favornum",-1);
            redisService.deleteCacheSetValue(key,sid);
        }else {
            //收藏操作
            redisService.incrementCacheMapValue(statisKey,"favornum",1);
            redisService.addCacheSetValue(key,sid);
            result = true;
        }
        Map<String, Object> cacheMap = redisService.getCacheMap(statisKey);
        cacheMap.put("result",result);

        return cacheMap;
    }
}
